#include <iostream>
#include <memory>
#include <string>

using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;
using std::string;

//对于shared_ptr，
//初始化、reset，都只能看到count为1，最终导致二次释放
//只有通过复制or赋值，才能保证那片空间的count+1

class Point{
public:
    Point(int ix,int iy)
    : _ix(ix)
    , _iy(iy)
    {
        cout<<"Point(int,int)"<<endl;
    }

    void print(){
        cout<<_ix<<","<<_iy<<endl;
    }

    ~Point(){
        cout<<"~Point()"<<endl;
    }

private:
    int _ix;
    int _iy;
};

void test(){
    Point *pint=new Point(1,2);
    Point *pint2=new Point(3,4);
    shared_ptr<Point> sp(pint);
    cout<<sp.use_count()<<endl;

    //shared_ptr<Point> sp2(pint);  //初始化，count还是1，导致二次释放
    shared_ptr<Point> sp2=sp;     //通过复制或者赋值，才可以保证引用计数+1
    cout<<sp2.use_count()<<endl;

    cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
    
    //shared_ptr<Point> sp3(sp);//拷贝构造，可以正确使用
    shared_ptr<Point> sp3(pint2);
    cout<<sp3.use_count()<<endl;
    sp3=sp; //通过复制或者赋值，才可以保证引用计数+1，且此时pint2的count为0，sp3把它释放了
    cout<<sp.use_count()<<endl;
    cout<<sp2.use_count()<<endl;
    cout<<sp3.use_count()<<endl;
}

void test1(){
    shared_ptr<Point> sp(new Point(1,2));
    sp->print();
    cout<<sp.use_count()<<endl;
    shared_ptr<Point> sp2(new Point(3,4));
    sp2->print();
    cout<<sp2.use_count()<<endl;

    cout<<endl;
    sp.reset(sp2.get());
    sp->print();
    sp2->print();
    cout<<sp.use_count()<<endl;
    cout<<sp2.use_count()<<endl;
    //引用计数都为1，double free
}

int main()
{   
    test();
    return 0;
}

